import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        //先进后出
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> back = new ArrayList<>();

        if (root == null) {
            return back;
        }

        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            back.add(node.val);

            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }

        return back;
    }
}

// 二叉树节点定义
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class PreorderTraversal {
    public static void main(String[] args) {
        // 构建测试用的二叉树
        //       1
        //        \
        //         2
        //        /
        //       3
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        // 创建解决方案实例
        Solution solution = new Solution();

        // 执行前序遍历
        List<Integer> result = solution.preorderTraversal(root);

        // 输出结果
        System.out.print("前序遍历结果: ");
        for (int num : result) {
            System.out.print(num + " ");
        }
        // 预期输出: 1 2 3
    }
}